<template>
  <div class="ammeter-tree">
    <div class="search-box">
      <el-input
        v-model="searchText"
        placeholder="请输入关键字进行过滤"
        prefix-icon="el-icon-search"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
      />
      <div class="tree-buttons">
        <i :class="isExpanded ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" @click="toggleExpand"></i>
      </div>
    </div>
    <div class="tree-container">
      <el-tree
        ref="tree"
        :data="treeData"
        :props="defaultProps"
        :filter-node-method="filterNode"
        node-key="id"
        :expand-on-click-node="false"
        default-expand-all
        highlight-current
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <div class="node-left">
            <i :class="getIcon(data.type)" :style="{ color: getIconColor(data.type) }"></i>
            <span>{{ node.label }}</span>
          </div>
          <span v-if="data.type === 'slave'" class="preview-btn" @click.stop="handlePreview(data)">预览图片</span>
        </span>
      </el-tree>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="50%"
      center
      append-to-body
      :style="{ right: '0', marginRight: '200px' }"
    >
      <div class="preview-image-container">
        <img v-if="previewImageUrl" :src="previewImageUrl" class="preview-image" />
        <div v-else class="no-image">暂无图片</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAmmeterTree } from "@/api/mes/bm/ammeter";

export default {
  name: "AmmeterTree",
  data() {
    return {
      treeData: [],
      searchText: "",
      isExpanded: true,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      previewVisible: false,
      previewImageUrl: ''
    };
  },
  created() {
    this.getTreeData();
  },
  methods: {
    getTreeData() {
      getAmmeterTree().then(response => {
        if (response.code === 200 && response.data) {
          this.treeData = this.formatTreeData(response.data);
          this.isExpanded = true;
        }
      });
    },
    formatTreeData(data) {
      if (!data || data.length === 0) {
        return [];
      }

      const rootName = data[0]?.bmMonitor?.psectorName || "北化浩绅";
      const root = {
        id: '0',
        name: rootName,
        type: 'master',
        children: []
      };

      data.forEach(item => {
        if (item.bmMonitor) {
          const monitorNode = {
            id: item.bmMonitor.id,
            name: item.bmMonitor.name,
            type: 'slave',
            children: [],
            sectorPicPath: item.bmMonitor.sectorPicPath
          };

          if (item.bmAmmeterList && Array.isArray(item.bmAmmeterList)) {
            monitorNode.children = item.bmAmmeterList.map(ammeter => ({
              id: ammeter.id,
              name: ammeter.name,
              type: 'ammeter',
              monitorId: ammeter.monitorId
            }));
          }

          root.children.push(monitorNode);
        }
      });

      return [root];
    },
    getIcon(type) {
      switch (type) {
        case 'master':
          return 'el-icon-s-home';
        case 'slave':
          return 'el-icon-office-building';
        case 'ammeter':
          return 'el-icon-data-line';
        default:
          return 'el-icon-s-home';
      }
    },
    getIconColor(type) {
      switch (type) {
        case 'master':
          return '#409EFF';  // 蓝色
        case 'slave':
          return '#67C23A';  // 绿色
        case 'ammeter':
          return '#E6A23C';  // 橙色
        default:
          return '#409EFF';
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    handleSearch(value) {
      this.$refs.tree.filter(value);
    },
    handleNodeClick(data) {
      this.$emit('node-click', {
        id: data.id,
        type: data.type,
        name: data.name
      });
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
      const nodes = this.$refs.tree.store.nodesMap;
      Object.keys(nodes).forEach(key => {
        nodes[key].expanded = this.isExpanded;
      });
    },
    handlePreview(data) {
      this.previewImageUrl = data.sectorPicPath;
      this.previewVisible = true;
    }
  }
};
</script>

<style scoped>
.ammeter-tree {
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-box {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.tree-buttons {
  display: flex;
  gap: 5px;
}

.tree-buttons i {
  font-size: 18px;
  cursor: pointer;
  color: #333;
  transition: transform 0.3s;
}

.tree-buttons i:hover {
  color: #666;
}

.tree-container {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 16px;
  box-sizing: border-box;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
}

.node-left {
  display: flex;
  align-items: center;
}

.node-left i {
  margin-right: 5px;
  font-size: 18px;
}

.preview-btn {
  margin-left: auto;
  color: #409EFF;
  font-size: 14px;
  cursor: pointer;
}

.preview-btn:hover {
  text-decoration: underline;
}

.preview-image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
}

.no-image {
  color: #909399;
  font-size: 14px;
}
</style>